<?php


namespace app\api\controller;

use think\Db;
use think\Request;
use app\admin\model\SaasBusiness;
use app\admin\model\SaasGoods;
use app\admin\model\SaasOrder as SO;
use app\admin\model\SaasBOrder as SBO;
use app\admin\model\SaasGoodsSpecs as SGS;

class SaasOrder extends Base
{
    /***
     * 创建订单
     * user_id
     * cart_id
     * addr
     *
     * order表
     * order_code varchar(255) 订单编号
     * user_id int(11) 用户id
     * pay_price decimal(10,2) 实际支付金额 ( 支付接口回调金额 )
     * pay_type tinyint(1)  支付方式  1微信   2支付宝
     * addr varchar(255) 收货地址
     * status tinyint(1) 订单状态  \n1未付款   \n2已付款  3订单失效
     * create_time int(11) 订单创建时间
     * pay_time int(11) 支付时间
     * invalid_time int(11) 订单失效时间
     *
     * b_order表
     * b_id 商家id
     * order_code varchar(255) 订单号
     * goods_id int(10)
     * specs_id int(10) 规格id
     * is_group_buying tinyint(1) 是否团购  1单品   2团购
     * goods_number int(10) 商品数量
     * goods_price decimal(10,2) 商品价格
     * status tinyint(1) 状态  1未付款    2未发货     3已发货    4已签收   5退货退款    6订单失效
     * express_code varchar(255) 快递单号
     * express_name varchar(255) 快递名称
     * send_goods_time int(11) 发货时间
     * take_time int(11) 收货时间
     *
     */
    public function createOrder(Request $request){
        $res = [];
        $data = $request->post();
        //order
        $addOrderData['order_code'] = date('ymd').uniqid(time());
        $addOrderData['addr'] = $data['addr'];
        $addOrderData['user_id'] = $data['user_id'];
        foreach($this->object_array(json_decode($data['goods_info'])) as $k=>$v){
            $totalPrice[] = $v['goods_number'] * $v['goods_price'];
        }
        $rs['totalPrice'] = array_sum($totalPrice);
        $addOrderData['pay_price'] = $rs['totalPrice'];
        $addOrderData['pay_type'] = $data['pay_type'];
        $addOrderData['status'] = 1;
        $addOrderData['create_time'] = time();
        $addOrderData['pay_time'] = 0;
        $addOrderData['invalid_time'] = strtotime('+5minute');

        //b_order
        foreach ($this->object_array(json_decode($data['goods_info'])) as $k=>$v){
            $addBOrderData[$k]['b_id'] = $v['b_id'];
            $addBOrderData[$k]['order_code'] = $addOrderData['order_code'];
            $addBOrderData[$k]['goods_id'] = $v['goods_id'];
            $addBOrderData[$k]['specs_id'] = $v['specs_id'];
            $addBOrderData[$k]['is_group_buying'] = $v['is_group_buying'];
            $addBOrderData[$k]['goods_number'] = $v['goods_number'];
            $addBOrderData[$k]['goods_price'] = $v['goods_price'];
            $addBOrderData[$k]['status'] = 1;
            $addBOrderData[$k]['express_code'] = '';
            $addBOrderData[$k]['express_name'] = '';
            $addBOrderData[$k]['send_goods_time'] = 0;
            $addBOrderData[$k]['take_time'] = 0;
            $addBOrderData[$k]['invalid_time'] = strtotime('+5 minute');
        }

        $bool = true;
        Db::startTrans();
        try{
            Db::table('app_saas_order')->insert($addOrderData);
            foreach ($addBOrderData as $v){
                $rs = Db::table('app_saas_b_order')->insert($v);
                if (!$rs){
                    // 回滚事务
                    Db::rollback();
                    $bool = false;
                }
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $bool = false;
        }
        if($bool){
            $res['data']['code'] = 1;
            $res['data']['msg'] = '创建成功';
        }else{
            $res['data']['code'] = 0;
            $res['data']['msg'] = '创建失败';
        }
        $res['status'] = 200;
        echo json_encode($res);
    }

    /***
     * @param Request $request
     * 用户订单列表
     * user_id
     */
    public function userSaasOrderList(Request $request){
        $res = [];
        $data = $request->post();
        if(!isset($data['user_id'])){
            $res['status'] = 400;
            echo json_encode($res);die;
        }

        $so = new SO();
        $sbo = new SBO();
        $where['user_id'] = $data['user_id'];
        $rs = $so->getAll($where);
        foreach ($rs as $k=>$v){
            $whereSBO['order_code'] = $v['order_code'];
            foreach ($sbo->getAllJoinGoods($whereSBO) as $n){
                $newrs[] = $n;
            }
        }

        if($newrs){
            $res['data']['code'] = 1;
            $res['data']['msg'] = "查询成功";
            $res['data']['list'] = $newrs;
        }else{
            $res['data']['code'] = 0;
            $res['data']['msg'] = "查询失败";
        }
        $res['status'] = 200;
        echo json_encode($res);
    }


    /***
     * 准备支付订单的详情
     * @param Request $request
     * order_code 订单编号
     * user_id 用户id
     */
    public function saasOrderPayDetail(Request $request){
        $res = [];
        $data = $request->post();
        if(!isset($data['order_code']) or !isset($data['user_id'])){
            $res['status'] = 400;
            echo json_encode($res);die;
        }

        $saasOrder = new SO();
        $where['order_code'] = $data['order_code'];
        $where['user_id'] = $data['user_id'];
        $rs = $saasOrder->getOne($where);
        if(!$rs){
            $res['data']['code'] = 0;
            $res['data']['msg'] = "用户订单不存在";
            $res['status'] = 200;
            echo json_encode($res);die;
        }
        $info = $this->object_array(json_decode($rs['order_info']));
        $sg = new SaasGoods();
        $sb = new SaasBusiness();
        foreach($info as $k=>$v){
            $totalPrice[] = $v['goods_number'] * $v['goods_price'];
            $goodsWhere['id'] = $v['goods_id'];
            $goodsInfo[] = $sg->getOneMore($goodsWhere);
        }
        $rs['totalPrice'] = array_sum($totalPrice);
        $rs['goods_info'] = $goodsInfo;
        if($rs){
            $res['data']['code'] = 1;
            $res['data']['msg'] = "查询成功";
            $res['data']['list'] = $rs;
        }else{
            $res['data']['code'] = 0;
            $res['data']['msg'] = "查询失败";
        }
        $res['status'] = 200;
        echo json_encode($res);
    }

    /***
     * 后台支付订单(伪支付，后期完善)
     * @param Request $request
     *
     */
    public function sassPayOrder(Request $request){
        $res = [];
        $data = $request->post();
        if(!isset($data['order_code'])){
            $res['status'] = 400;
            echo json_encode($res);die;
        }

        $sbo = new SBO();
        $so = new SO();
        //统计订单价格
        $where['order_code'] = $data['order_code'];
        $rs = $sbo->getAll($where);
        if(!$rs){
            $res['data']['code'] = 0;
            $res['data']['msg'] = "支付失败";
            $res['status'] = 200;
            echo json_encode($res);die;
        }
        foreach($rs as $k=>$v){
            $totalPrice[] = $v['goods_number'] * $v['goods_price'];
        }

        //支付环节省略
        array_sum($totalPrice);

        $bool = true;
        Db::startTrans();
        try{
            //修改小订单
            $editSboData['status'] = 2;
            $editSboData['pay_time'] = time();
            $sbo->edit($where,$editSboData);
            //修改大订单
            $editSoData['status'] = 2;
            $editSoData['pay_time'] = time();
            $so->edit($where,$editSoData);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $bool = false;
        }
        if($bool){
            $res['data']['code'] = 1;
            $res['data']['msg'] = "支付成功";
        }else{
            $res['data']['code'] = 0;
            $res['data']['msg'] = "支付失败";
        }
        $res['status'] = 200;
        echo json_encode($res);
    }

    /***
     * @param Request $request
     * 修改订单状态
     * user_id
     * order_code
     * status
     */
    public function changeOrderStatus(Request $request){
        $res = [];
        $data = $request->post();
        if(!isset($data['order_code']) or !isset($data['user_id']) or !isset($data['id']) or !isset($data['status'])){
            $res['status'] = 400;
            echo json_encode($res);die;
        }

        //查询是否有此订单
        $so = new SO();
        $where['user_id'] = $data['user_id'];
        $where['order_code'] = $data['order_code'];
        if(!$so->getOne($where)){
            $res['data']['code'] = 0;
            $res['data']['msg'] = "订单信息错误";
            $res['status'] = 200;
            echo json_encode($res);die;
        }

        //修改小订单
        $sbo = new SBO();
        $editWhere['order_code'] = $data['order_code'];
        $editWhere['id'] = $data['id'];
        $editData['status'] = $data['status'];
        $editData['pay_time'] = time();
        if($sbo->edit($editWhere,$editData)){
            $res['data']['code'] = 1;
            $res['data']['msg'] = "修改状态成功";
        }else{
            $res['data']['code'] = 0;
            $res['data']['msg'] = "修改状态失败";
        }
        $res['status'] = 200;
        echo json_encode($res);
    }


    ######################################################
    ####################  商家操作  #######################
    ######################################################

    /***
     * @param Request $request
     * 查看订单
     */
    public function businessGetOrderList(Request $request){
        $res = [];
        $data = $request->post();
        if(!isset($data['user_id'])){
            $res['status'] = 400;
            echo json_encode($res);die;
        }
        $sbo = new SBO();
        $sgs = new SGS();
        $sg = new SaasGoods();
        $sb = new SaasBusiness();
        $so = new SO();

        //查询商家的店铺id
        $getBid = $sb->getOne($data);
        $where['b_id'] = $getBid['id'];
        $where['status'] = ['in',[2,3]];
        $rs = $sbo->getAll($where);
        foreach($rs as $k=>$v){
            //产品规格
            $whereSgs['id'] = $v['specs_id'];
            $sgsRs = $sgs->getOne($whereSgs);
            $rs[$k]['specs_name'] = $sgsRs['specs_name'];
            //产品名称
            $whereSg['id'] = $v['goods_id'];
            $sgRs = $sg->getOne($whereSg);
            $rs[$k]['goods_name'] = $sgRs['goods_name'];
            //产品名称
            $whereSg['id'] = $v['goods_id'];
            $sgRs = $sg->getOne($whereSg);
            $rs[$k]['goods_name'] = $sgRs['goods_name'];
            $rs[$k]['goods_img'] = $sgRs['img'];
            //店铺名
            $whereSb['id'] = $where['b_id'];
            $sbRs = $sb->getOne($whereSb);
            $rs[$k]['sb_name'] = $sbRs['name'];
            //收货地址
            $whereSo['order_code'] = $v['order_code'];
            $soRs = $so->getOne($whereSo);
            $rs[$k]['addr'] = $soRs['addr'];
        }

        if($rs){
            $res['data']['code'] = 1;
            $res['data']['msg'] = "查询成功";
            $res['data']['list'] = $rs;
        }else{
            $res['data']['code'] = 0;
            $res['data']['msg'] = "查询失败";
        }
        $res['status'] = 200;
        echo json_encode($res);
    }

    /***
     * @param Request $request
     * 商家修改发货信息
     * user_id
     */
    public function editOrderExpress(Request $request){
        $res = [];
        $data = $request->post();
        if(!isset($data['id']) or !isset($data['b_id']) or !isset($data['express_code']) or !isset($data['express_name'])){
            $res['status'] = 400;
            echo json_encode($res);die;
        }

        $sbo = new SBO();
        $where['id'] = $data['id'];
        $where['b_id'] = $data['b_id'];
        $editData['status'] = 3;
        $editData['express_code'] = $data['express_code'];
        $editData['express_name'] = $data['express_name'];
        $editData['send_goods_time'] = time();
        if($sbo->edit($where,$editData)){
            $res['data']['code'] = 1;
            $res['data']['msg'] = "修改成功";
        }else{
            $res['data']['code'] = 0;
            $res['data']['msg'] = "修改失败";
        }
        $res['status'] = 200;
        echo json_encode($res);
    }

}